#encoding:utf-8
from flask import Flask, request, render_template, make_response, jsonify
import pymysql
import hashlib
import random

app = Flask(__name__)
app.secret_key = 'thisismy2021course'

def sql():
    # conn = pymysql.connect(host='localhost', user="root", passwd="f5a10ef2dd4f5e90", database="userLogin")
    conn = pymysql.connect(host='user-db', user="root", passwd="123456", database="userSys")
    cursor = conn.cursor()

    return conn, cursor

def md5(psd):
    m = hashlib.md5()
    m.update(psd.encode("utf8"))

    return m.hexdigest()
 

@app.route("/", methods=['GET', 'POST'])
@app.route('/Page_register.html', methods=['GET', 'POST'])
def hello():
    if request.method == "GET":
        return render_template("/Page_register.html")

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == "POST":
        connect, cursor = sql()
        user = request.json
        stuName = user['stuName']
        stuID = user['stuID']
        stuPhone = user['stuPhone']
        password = user['password_1']
        userSex = user['userSex']

        sql_selectUser = "SELECT id FROM `usersInfo` WHERE stuID=\'%s\'" % stuID
        cursor.execute(sql_selectUser)
        anyUser = cursor.fetchall()
        if anyUser:
            return make_response(jsonify({ 'msg': '', 'error': '注册失败', 'content': '用户名已存在' }), 200)

        password = str(md5(str(password)))
        sql_insertUserInfo = "insert into usersInfo(stuID, stuName, stuSex, stuPhone, can_choose) values('%s', '%s', %d, '%s', %d)" % (stuID, stuName, int(userSex), stuPhone, 1)
        cursor.execute(sql_insertUserInfo)
        connect.commit()
        
        sql_selectId = "select id from `usersInfo` where stuID=\'%s\'" % stuID
        cursor.execute(sql_selectId)
        userId = cursor.fetchone()
        
        sql_insertUser = "insert into users(uid, userName, userPswd, is_del) values(%d, '%s', '%s', %d)" % (int(userId[0]), stuID, password, 0)
        cursor.execute(sql_insertUser)
        connect.commit()
        
        veriNum = "".join([str(random.randint(0, 9)) for _ in range(6)])
        sql_insertVeri = "insert into verification(uid, verifyNum) values(%d, '%s')" % (int(userId[0]), veriNum)
        cursor.execute(sql_insertVeri)
        connect.commit()
        
        return make_response(jsonify({ 'msg': '注册成功！', 'error': '', 'content': '请返回登录' }), 200)


app.run(host='0.0.0.0', port=3354)
